package com.jinrustar.op.core.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jinrustar.op.core.exception.BaseException;
import com.jinrustar.op.core.exception.IllegalParameterException;
import com.jinrustar.op.core.support.HttpCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*import org.apache.shiro.authz.UnauthorizedException;*/

/**
 * 控制器基类
 */
public abstract class BaseController {

    public BaseController(){
        System.out.println("####### BaseController ####### constructor");
    }


    /**
     * 获取当前用户Id
     */
    /*protected Long getCurrUser() {
        return WebUtil.getCurrentUser();
    }*/

    /**
     * 设置成功响应代码
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
        return setSuccessModelMap(modelMap, null);
    }

    /**
     * 设置成功响应代码
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
        return setModelMap(modelMap, HttpCode.OK, data);
    }

    /**
     * 设置响应代码
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
        return setModelMap(modelMap, code, null);
    }

    /**
     * 设置响应代码
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
        modelMap.remove("void");
        if (data != null) {
            modelMap.put("data", data);
        }
        modelMap.put("httpCode", code.value());
        modelMap.put("msg", code.msg());
        modelMap.put("timestamp", System.currentTimeMillis());

//		return ResponseEntity.ok(modelMap);

        /*增加响应头, 允许前端跨域(已修改为在Nginx配置 location / { add_header Access-Control-Allow-Origin "http://100.100.1.101:8080";})*//*
        /*HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        httpHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://100.100.1.101:8080");
        return new ResponseEntity(modelMap, httpHeaders, HttpStatus.OK);*/

        return new ResponseEntity(modelMap, HttpStatus.OK);
    }


    /**
     * 统一异常处理
     */
    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
            throws Exception {
        /*logger.error(Constants.Exception_Head, ex);*/
        ModelMap modelMap = new ModelMap();
        ex.printStackTrace();
        if (ex instanceof BaseException) {
            ((BaseException) ex).handler(modelMap);
        } else if (ex instanceof IllegalArgumentException) {
            new IllegalParameterException(ex.getMessage()).handler(modelMap);
        } /*else if (ex instanceof UnauthorizedException) {
            setModelMap(modelMap, HttpCode.FORBIDDEN);
        }*/ else {
            setModelMap(modelMap, HttpCode.INTERNAL_SERVER_ERROR);
        }
        request.setAttribute("msg", modelMap.get("msg"));
        response.setContentType("application/json;charset=UTF-8");
        /*byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);*/

        byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
        response.getOutputStream().write(bytes);
    }


    /**
     * for dataTable
     *
     * @param draw
     * @param total
     * @param filterTotal
     * @param data
     * @return
     */
    public Object setSuccessDataForFrontendDatatable(int draw, int total, int filterTotal, Object data) {
        Map map = new HashMap();
        map.put("draw", draw);
        map.put("recordsTotal", total);
        map.put("recordsFiltered", filterTotal);
        map.put("data", data);
        return JSON.parse(handleJsonStr(JSON.toJSONString(map)));
    }

    static public String handleJsonStr(String jsonString) {
        /*转换id长整型为字符串(解决前端无法处理的问题)*/

        Pattern pattern = Pattern.compile("(\"\\:\\d+\\.*\\d+)");
        String inputStr = jsonString;

        inputStr = inputStr.replaceAll("\\\\r", "").replaceAll("\\\\n", "").replaceAll("\\r\\n", "").replaceAll("\\\\\"", "\"");

        /*System.out.println(inputStr);*/
        Matcher matcher = pattern.matcher(inputStr);
        while (matcher.find()) {
            /*System.out.println("###" + matcher.group(0));
            System.out.println("###" + matcher.group(1));*/

            inputStr = inputStr.replaceAll(matcher.group(), "\":" + "\"" + matcher.group(1).substring(2) + "\""); /**/
        }


        /*inputStr = inputStr.replaceAll("\\\"","");*/

        return inputStr;
    }
}